package com.awspaas.user.apps.processforsap.util;

import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.AbstFileProcessor;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.FileProcessorListener;
import com.actionsoft.bpms.util.UtilFile;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.util.Map;

public class ProjectDataExcelImpl extends AbstFileProcessor implements FileProcessorListener {

    private static final String EXTENSION_XLS = ".xls";
    private static final String EXTENSION_XLSX = ".xlsx";

    @Override
    public void uploadBeforeEncrypt(Map<String, Object> param) {
        super.uploadBeforeEncrypt(param);
    }

    @Override
    public void uploadSuccess(Map<String, Object> param) {
        //文件存储
        DCContext context = (DCContext) param.get("DCContext");
        //上传人
        UserContext uc = context.getSession();
        String fileName = context.getFileName();
        UtilFile tmpFile = new UtilFile(context.getFilePath());

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(context.getFilePath());
            //得到Excel工作簿对象
            Workbook wb = null;
            int available = inputStream.available();
            if (available >= 2000000) {//大于2m的文件给与提示
                context.getDCMessage().setMessage("文件过大会读取异常，请传入小于2m大小的文件或者尝试清除没有数据的单元格样式！！！");
                return;
            }
            if (context.getFilePath().endsWith(EXTENSION_XLS)) {
                wb = new HSSFWorkbook(inputStream);
            } else if (context.getFilePath().endsWith(EXTENSION_XLSX)) {
                wb = new XSSFWorkbook(inputStream);
            }

            if (wb == null) {
                context.getDCMessage().setMessage("读取文件错误");
                return;
            }
            // 创建数据（包含图片）
            context.getDCMessage().setMessage("导入成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            context.getDCMessage().setMessage("读取文件错误");
        } finally {
            // 删除
            tmpFile.delete();
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception var23) {
                }
            }
        }
    }
}